/**
 * Author : Fengyuan(Franklin) Zhang
 * Date : 2019/1/2
 * Description : Common Method
 */

var crypto = require('crypto');
var stringRandom = require('string-random');
var path = require('path');

var CommonMethod = function () {}

module.exports = CommonMethod;

//! encryption
CommonMethod.crypto = function(buffer){
    //! hex
    buffer = new Buffer(buffer).toString('hex')

    //! base64
    buffer = new Buffer(buffer).toString('base64');

    //! confusion
    buffer = stringRandom(5, {specials: true}) + buffer + stringRandom(5, {specials: true});

    //! base64
    buffer = new Buffer(buffer).toString('base64');

    return buffer;
};

//! decryption
CommonMethod.decrypto = function(buffer){
    try{
        //! de base64
        buffer = new Buffer(buffer, 'base64').toString();

        //! de confusion
        buffer = buffer.substr(5);
        buffer = buffer.substr(0, buffer.length - 5);

        //! de base64
        buffer = new Buffer(buffer, 'base64').toString();

        //! de hex
        buffer = new Buffer(buffer, 'hex').toString();
        return buffer;
    }
    catch(ex){
        return "";
    }
};

//! get MD5
CommonMethod.md5 = function(buffer){
    return crypto.createHash('md5').update(buffer).digest('hex');
};

//! get data file path
CommonMethod.getDataPath = function () {
    return path.dirname(process.execPath) + '/data/';
    // return __dirname + '/../data/';
}